package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpMapper;
import com.itheima.mapper.EmpExprMapper;

import java.time.LocalDateTime;
import java.util.stream.Collectors;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {
    @Autowired
    private DeptService deptService;
    @Autowired
    private EmpExprService empExprService;

    @Override
    public PageResult<Emp> getPageResult(EmpQueryParam param) {
        Page<Emp> page = Page.of(param.getPage(), param.getPageSize());

        // 添加按更新时间降序排序
        page.addOrder(OrderItem.desc("update_time"));

        // 构建查询条件
        page = lambdaQuery()
                .like(param.getName() != null && !param.getName().isEmpty(), Emp::getName, param.getName())
                .eq(param.getGender() != null, Emp::getGender, param.getGender())
                .between(param.getBegin() != null && param.getEnd() != null, Emp::getUpdateTime, param.getBegin(), param.getEnd())
                .page(page);

        //获取员工集合
        List<Emp> emps = page.getRecords();

        //获取所有员工部门id
        // 获取所有员工部门id
        List<Integer> deptIds = emps.stream()
                .map(Emp::getDeptId)
                .collect(Collectors.toList());
        if(!deptIds.isEmpty()){
            List<Dept> depts = deptService.listByIds(deptIds);


        // 将部门名称封装到员工对象中
        emps.forEach(emp -> {
            depts.forEach(dept -> {
                if (emp.getDeptId() != null && emp.getDeptId().equals(dept.getId())) {
                    emp.setDeptName(dept.getName());
                }
            });
        });
    }

        // 封装返回结果
        return new PageResult<>(page.getTotal(), emps);
    }

    @Override
    public void saveEmp(Emp emp) {
        /** 新增员工*/
        emp.setUpdateTime(LocalDateTime.now());
        emp.setCreateTime(LocalDateTime.now()); //补全时间
        save(emp);


        /**调用service方法保存员工工作经历*/
        List<EmpExpr> exprList = emp.getExprList();
        if(!exprList.isEmpty()){
            exprList.forEach(expr -> expr.setEmpId(emp.getId()));
            empExprService.saveBatch(exprList);


        }

    }

    @Override
    public Emp getEmpById(Integer id) {
        //查询员工基本信息
        Emp emp = getById(id);
        //查询员工工作经历
        List<EmpExpr> empExprList = empExprService.lambdaQuery().eq(EmpExpr::getEmpId, id).list();

        // 将员工工作经历集合封装到员工对象中
        emp.setExprList(empExprList);

        return emp;
    }

    @Override
    public void updateEmp(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        updateById(emp);
        empExprService.remove(
                empExprService.lambdaQuery().eq(EmpExpr::getEmpId, emp.getId())
        );
//批量保存
        List<EmpExpr> exprList = emp.getExprList();
        if(exprList != null && !exprList.isEmpty()){
            exprList.forEach(expr -> expr.setEmpId(emp.getId()));
        }
        empExprService.saveBatch(exprList);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeEmpsByIds(List<Integer> ids) {
        removeByIds(ids);
      //批量删除员工工作经历
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().in(EmpExpr::getEmpId, ids)
        );
    }


}
